package com.freesky.provider.search.service.impl;

import com.freesky.common.exception.EMallException;
import com.freesky.common.utils.reponse.JSONResponse;
import com.freesky.common.utils.reponse.JSONResponseDiretor;
import com.freesky.provider.search.service.ISearchService;
import com.freesky.provider.search.vo.SearchItem;
import com.freesky.provider.search.vo.SearchItemName;
import com.freesky.provider.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SearchServiceImpl implements ISearchService {

    @Autowired
    private SolrClient client;


    @Value("${solr.core}")
    private String coreName;

    @Override
    public JSONResponse search(String key, int page, int size, String sort, int priceGt, int priceLte) {

        try {
            key=key.replace(" ", "\\ ");

            SearchResult searchResult = new SearchResult();
            //设置分页
            if (page <= 0) {
                page = 1;
            }
            int start = (page - 1) * size;

            QueryResponse response = null;
            if (priceGt >= 0 && priceLte >= 0 && sort.isEmpty()) {
                SolrQuery query = new SolrQuery();
                query.set("q", "itemName:*" + key + "*");
                //开始位置
                query.setStart(start);
                //每页3条
                query.setRows(size);
                query.set("fq", String.format("salePrice:[%d TO %d]", priceGt, priceLte));

                response = client.query(coreName, query);

            } else if (priceGt >= 0 && priceLte >= 0 && sort.equals("1")) {
                SolrQuery query = new SolrQuery();
                query.set("q", "itemName:*" + key + "*");
                query.setStart(start);
                query.setRows(size);
                query.set("fq", String.format("salePrice:[%d TO %d]", priceGt, priceLte));
                query.addSort("salePrice", SolrQuery.ORDER.asc);
                response = client.query(coreName, query);
            } else if (priceGt >= 0 && priceLte >= 0 && sort.equals("-1")) {
                SolrQuery query = new SolrQuery();
                query.set("q", "itemName:*" + key + "*");
                query.setStart(start);
                query.setRows(size);
                query.set("fq", String.format("salePrice:[%d TO %d]", priceGt, priceLte));
                query.addSort("salePrice", SolrQuery.ORDER.desc);
                response = client.query(coreName, query);
            } else if ((priceGt < 0 || priceLte < 0) && sort.isEmpty()) {
                SolrQuery query = new SolrQuery();
                query.set("q", "itemName:*" + key + "*");
                query.setStart(start);
                query.setRows(size);
                response = client.query(coreName, query);
            } else if ((priceGt < 0 || priceLte < 0) && sort.equals("1")) {
                SolrQuery query = new SolrQuery();
                query.set("q", "itemName:*" + key + "*");
                query.setStart(start);
                query.setRows(size);
                query.addSort("salePrice", SolrQuery.ORDER.asc);
                response = client.query(coreName, query);
            } else if ((priceGt < 0 || priceLte < 0) && sort.equals("-1")) {
                SolrQuery query = new SolrQuery();
                query.set("q", "itemName:*" + key + "*");
                query.setStart(start);
                query.setRows(size);
                query.addSort("salePrice", SolrQuery.ORDER.desc);
                response = client.query(coreName, query);
            }
            //查询结果
            SolrDocumentList results = response.getResults();

            //返回总结果数
            List<SearchItem> list = response.getBeans(SearchItem.class);
            if (results != null) {
                long totalCount = results.getNumFound();
                searchResult.setRecordCount(totalCount);
                long pageSize = (totalCount + size - 1) / size;
                searchResult.setTotalPages((int) pageSize);
                searchResult.setItemList(list);
            }
            searchResult.setItemList(list);
            return JSONResponseDiretor.buildSuccessJSONResponse(searchResult);
        } catch (Exception e) {
            log.error("查询Solr索引失败", e);
            throw new EMallException("查询失败");
        }
    }

    @Override
    public JSONResponse getItemNameListByKeyWords(String key) {
        List<SearchItemName> list = new ArrayList<>();
        try {
            QueryResponse response;
            SolrQuery query = new SolrQuery();
            query.setFields("itemName");
            query.set("q", "itemName:*" + key + "*");
            response = client.query(coreName, query);
            //查询结果
            if (response.getResults().getNumFound() > 0) {
                for (SolrDocument doc : response.getResults()) {
                    SearchItemName itemName = new SearchItemName();
                    log.info(doc.get("itemName").toString());
                    itemName.setValue(doc.get("itemName").toString());
                    list.add(itemName);
                }
            }
            return JSONResponseDiretor.buildSuccessJSONResponse(list);
        } catch (Exception e) {
            log.error("查询Solr索引失败", e);
            throw new EMallException("查询失败");
        }
    }

}
